package dao.impl;

import dao.BaseDAO;
import dao.StoreDAO;
import entity.Storehouse;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by asus on 2017/6/22.
 */
@Repository("storeDAO")
public class StoreDAOImpl extends BaseDAO implements StoreDAO {
    private class StoreMapper implements RowMapper<Storehouse> {
        @Override
        public Storehouse mapRow(ResultSet resultSet, int i) throws SQLException {
            Storehouse storehouse=new Storehouse();
            storehouse.setId(resultSet.getLong("id"));
            storehouse.setName(resultSet.getString("name"));
            storehouse.setAddress(resultSet.getString("address"));
            return storehouse;
        }
    }

    /**
     * 获取总记录数
     * @return
     */
    @Override
    public Integer getCount(){
        String sql="select count(*) from storehouse";
        try{
            return jdbcTemplate.queryForObject(sql,Integer.class);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }

    }

    @Override
    public Storehouse findById(Long id) {
        String sql = "select * from storehouse where id=?";
        try{
            return jdbcTemplate.queryForObject(sql, new Object[]{id}, new StoreMapper());
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public List<Storehouse> findPage(int page, int size) {
        if (page < 1) {
            page = 1;
        }
        if (size < 0) {
            size = 20;
        }
        String sql = "select * from storehouse limit ?,?";
        int skip = (page - 1) * size;
        try {
            return jdbcTemplate.query(sql, new Object[]{skip, size}, new StoreMapper());
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public List<Storehouse> findAll() {
        String sql="select * from storehouse";
        return jdbcTemplate.query(sql,new StoreMapper());
    }
}
